package com.xayy.ds.service.impl;

import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.base.utils.CollUtil;
import cn.kawins.mybatis.util.SnowflakeId;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xayy.ds.model.DsBridgeParam;
import com.xayy.ds.service.DsBridgeParamService;
import com.xayy.mgt.mapper.NodeInfoMapper;
import com.xayy.mgt.model.AssociationParameter;
import com.xayy.mgt.model.FunctionalIndicators;
import com.xayy.mgt.model.vo.HealthDeepVo;
import com.xtck.ha.common.core.domain.R;
import com.xtck.ha.common.core.web.service.dsimpl.BaseServiceImpl;
import com.xtck.ha.common.core.config.DsServerConfig;
import com.xtck.ha.common.core.utils.DomainUtils;
import com.xayy.ds.model.DsHealthDeep;
import com.xayy.ds.service.DsHealthDeepService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: DsHealthDeepService实现类
 * @Auther:liuyuan
 * @Date:2025-07-03
 */
@Slf4j
@Service
public class DsHealthDeepServiceImpl extends BaseServiceImpl<DsHealthDeep> implements DsHealthDeepService {
  /**
  *
  * 冗余代码，为自定义开发DS-Server接口服务
  *
  */
   private static String TABLE_NAME = "T_HEALTH_DEEP";
   private String getUrl(){
      return getDsServerConfig().getUrl();
   }

    @Autowired
    private DsBridgeParamService dsBridgeParamService;

    @Override
    @Transactional
    public CheckResult<Object> saveHealthDeep(HealthDeepVo healthDeepVo) {
        DsHealthDeep healthDeep = BeanUtil.copyBean(healthDeepVo, DsHealthDeep.class);
        CheckResult<?> checkName = checkName(false, healthDeep);
        if (checkName.no()) {
            return CheckResult.fail(checkName.getCheckMsg());
        }
        CheckResult<?> checkCode = checkCode(false, healthDeep);
        if (checkCode.no()) {
            return CheckResult.fail(checkCode.getCheckMsg());
        }
//        NodeTreeInfo nodeTreeInfo = nodeInfoMapper.selectByPrimaryKey(healthDeepVo.getNodeId());
//        NodeTreeInfo nodeTreeInfo = nodeInfoService.selectById(healthDeepVo.getNodeId());
//        CheckResult<?> checkSyntax = FunUtil.checkSyntax(nodeTreeInfo.getSatelliteId(), healthDeepVo.getNodeId(),
//                new Date(), healthDeepVo.getCustomParam());
//        if (checkSyntax.no()) {
//            return CheckResult.fail(checkSyntax.getCheckMsg());
//        }
        Long id = new SnowflakeId().genId("t_health_deep", "id");
        healthDeep.setId(id);
        insertT(healthDeep);
        // 将健康度id和功能性信息中间表添加
        List<Long> functionIds = healthDeepVo.getFunctionIds();
        // 将健康度id和性能能性信息中间表添加
        List<Long> performanceIds = healthDeepVo.getPerformanceIds();
        List<DsBridgeParam> bridgeParams = new ArrayList<>();
        if (CollUtil.isNotEmpty(functionIds)) {
            functionIds.forEach(x -> {
                DsBridgeParam bridgeParam = new DsBridgeParam();
                bridgeParam.setParentId(id);
                bridgeParam.setChildId(x);
                bridgeParam.setChildType(1);
                bridgeParam.setType(3);
                bridgeParams.add(bridgeParam);
            });
        }
        if (CollUtil.isNotEmpty(performanceIds)) {
            performanceIds.forEach(x -> {
                DsBridgeParam bridgeParam = new DsBridgeParam();
                bridgeParam.setParentId(id);
                bridgeParam.setChildId(x);
                bridgeParam.setChildType(2);
                bridgeParam.setType(3);
                bridgeParams.add(bridgeParam);
            });
        }
        if (CollUtil.isNotEmpty(bridgeParams))
            for (DsBridgeParam entity : bridgeParams){
                dsBridgeParamService.insertT(entity);
            }
        return CheckResult.success("新增成功");
    }

    @Override
    @Transactional
    public CheckResult<Object> updateHealthDeep(HealthDeepVo healthDeepVo) {
        DsHealthDeep healthDeep = BeanUtil.copyBean(healthDeepVo, DsHealthDeep.class);
        CheckResult<?> checkName = checkName(true, healthDeep);
        if (checkName.no()) {
            return CheckResult.fail(checkName.getCheckMsg());
        }
        CheckResult<?> checkCode = checkCode(true, healthDeep);
        if (checkCode.no()) {
            return CheckResult.fail(checkCode.getCheckMsg());
        }
//        NodeTreeInfo nodeTreeInfo = nodeInfoMapper.selectByPrimaryKey(healthDeepVo.getNodeId());
//        NodeTreeInfo nodeTreeInfo = nodeInfoService.selectById(healthDeepVo.getNodeId());
//        CheckResult<?> checkSyntax = FunUtil.checkSyntax(nodeTreeInfo.getSatelliteId(), healthDeepVo.getNodeId(),
//                new Date(), healthDeepVo.getCustomParam());
//        if (checkSyntax.no()) {
//            return CheckResult.fail(checkSyntax.getCheckMsg());
//        }
        updateT(healthDeep);
        // 将健康度id和功能性信息中间表添加
        List<Long> functionIds = healthDeepVo.getFunctionIds();
        // 将健康度id和性能能性信息中间表添加
        List<Long> performanceIds = healthDeepVo.getPerformanceIds();
        List<DsBridgeParam> bridgeParams = new ArrayList<>();
        if (CollUtil.isNotEmpty(functionIds)) {
            functionIds.forEach(x -> {
                DsBridgeParam bridgeParam = new DsBridgeParam();
                bridgeParam.setParentId(healthDeep.getId());
                bridgeParam.setChildId(x);
                bridgeParam.setChildType(1);
                bridgeParam.setType(3);
                bridgeParams.add(bridgeParam);
            });
        }
        if (CollUtil.isNotEmpty(performanceIds)) {
            performanceIds.forEach(x -> {
                DsBridgeParam bridgeParam = new DsBridgeParam();
                bridgeParam.setParentId(healthDeep.getId());
                bridgeParam.setChildId(x);
                bridgeParam.setChildType(2);
                bridgeParam.setType(3);
                bridgeParams.add(bridgeParam);
            });
        }
        dsBridgeParamService.deleteTList(DsBridgeParam.builder().parentId(healthDeep.getId()).type(3).build());
        if (CollUtil.isNotEmpty(bridgeParams))
            for (DsBridgeParam entity : bridgeParams){
                dsBridgeParamService.insertT(entity);
            }

        return CheckResult.success("修改成功");
    }

    @Override
    public CheckResult<DsHealthDeep> getHealthDeep(Long nodeId) {
        List<DsHealthDeep> list = selectTList(DsHealthDeep.builder().nodeId(nodeId).build());
        DsHealthDeep healthDeep = new DsHealthDeep();
        if (null != list && list.size()>0)
            healthDeep = list.get(0);
        return CheckResult.success(healthDeep);
    }

    @Override
    public DsHealthDeep getByNodeId(Long nodeId) {
        List<DsHealthDeep> list = selectTList(DsHealthDeep.builder().nodeId(nodeId).build());
        DsHealthDeep healthDeep = new DsHealthDeep();
        if (null != list && list.size()>0)
            healthDeep = list.get(0);
        return healthDeep;
    }

    @Override
    public CheckResult<HealthDeepVo> getHealthDeepVo(Long nodeId) {
        List<DsHealthDeep> list = selectTList(DsHealthDeep.builder().nodeId(nodeId).build());
        DsHealthDeep healthDeep = new DsHealthDeep();
        if (null != list && list.size()>0)
            healthDeep = list.get(0);
        if (BeanUtil.isNotEmpty(healthDeep)) {
            HealthDeepVo healthDeepVo = BeanUtil.copyBean(healthDeep, HealthDeepVo.class);
            List<DsBridgeParam> functions =
                    dsBridgeParamService.selectTList(DsBridgeParam.builder().parentId(healthDeep.getId()).childType(1).build());
            List<DsBridgeParam> performances =
                    dsBridgeParamService.selectTList(DsBridgeParam.builder().parentId(healthDeep.getId()).childType(2).build());
            List<Long> functionIds = functions.stream().map(DsBridgeParam::getChildId).collect(Collectors.toList());
            List<Long> performanceIds = performances.stream().map(DsBridgeParam::getChildId).collect(Collectors.toList());
            healthDeepVo.setFunctionIds(CollUtil.newArrayList(functionIds));
            healthDeepVo.setPerformanceIds(CollUtil.newArrayList(performanceIds));
            return CheckResult.success(healthDeepVo);
        }
        return CheckResult.success(new HealthDeepVo());
    }

    @Override
    @Transactional
    public CheckResult<Object> deleteByNodeId(Long id) {

        deleteTList(DsHealthDeep.builder().nodeId(id).build());
        DsBridgeParam deleteBody = DsBridgeParam.builder()
                .parentId(id)
                .build();
        dsBridgeParamService.deleteTList(deleteBody);
        return CheckResult.success("删除成功");
    }

    /**
     * 校验同节点下得健康度指标名称是否已存在
     *
     * @param isUpdate   是否更新
     * @param healthDeep 入参
     * @return 结果日志
     */
    private CheckResult<?> checkName(Boolean isUpdate, DsHealthDeep healthDeep) {
        DsHealthDeep selectBody = new DsHealthDeep();
        selectBody.setNodeId(healthDeep.getNodeId());
        selectBody.setMetricsName(healthDeep.getMetricsName());
        int i = 0;
        if (Boolean.TRUE.equals(isUpdate)) {
            List<DsHealthDeep> resultList = selectTList(selectBody);
            List<DsHealthDeep> list = new ArrayList<>();
            if (CollUtil.isNotEmpty(resultList)){
                for (DsHealthDeep healthDeep1 : resultList){
                    if ( !healthDeep1.getId().equals(healthDeep.getId()) ){
                        list.add(healthDeep1);
                    }
                }
                i = list.size();
            }
        }else {
            i = (int) count(selectBody);
        }

        if (i > 0) {
            return CheckResult.fail("指标名称：" + healthDeep.getMetricsName() + "已经存在");
        }
        return CheckResult.success();
    }

    /**
     * 校验同节点下得健康度指标code是否已存在
     *
     * @param isUpdate   是否更新
     * @param healthDeep 入参
     * @return 结果日志
     */
    private CheckResult<?> checkCode(Boolean isUpdate, DsHealthDeep healthDeep) {
        DsHealthDeep selectBody = new DsHealthDeep();
        selectBody.setNodeId(healthDeep.getNodeId());
        selectBody.setMetricsCode(healthDeep.getMetricsCode());
        int i = 0;
        if (Boolean.TRUE.equals(isUpdate)) {
            List<DsHealthDeep> resultList = selectTList(selectBody);
            List<DsHealthDeep> list = new ArrayList<>();
            if (CollUtil.isNotEmpty(resultList)){
                for (DsHealthDeep healthDeep1 : resultList){
                    if (!healthDeep1.getId().equals(healthDeep.getId()) ){
                        list.add(healthDeep1);
                    }
                }
                i = list.size();
            }
        }else {
            i = (int) count(selectBody);
        }
        if (i > 0) {
            return CheckResult.fail("指标代号：" + healthDeep.getMetricsCode() + "已经存在");
        }
        return CheckResult.success();
    }
}
